package com.viknix.threadpool.manager.server.controller.config;

import com.viknix.threadpool.manager.config.constant.Constants;
import com.viknix.threadpool.manager.config.dump.DumpService;
import com.viknix.threadpool.manager.config.service.impl.AsyncNotifyService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: Dongqi
 * @Date: 2021/11/18 19:43
 * @Version 1.0
 * @Description: 用于集群节点间相互通信
 */
@RestController
@AllArgsConstructor
@RequestMapping(Constants.COMMUNICATION_CONTROLLER_PATH)
public class CommunicationController {

    private final DumpService dumpService;

    private static final String trueStr = "true";

    /**
     * Notify the change of config information.
     * http://{0}{1}/communication/dataChange?dataId={2}&group={3}&tenant={4}
     */
    @GetMapping("/dataChange")
    public Boolean notifyConfigInfo(HttpServletRequest request, @RequestParam("dataId") String dataId,
                                    @RequestParam("group") String group,
                                    @RequestParam(value = "tenant", required = false, defaultValue = StringUtils.EMPTY) String tenant,
                                    @RequestParam(value = "tag", required = false) String tag) {
        dataId = dataId.trim();
        group = group.trim();
        String lastModified = request.getHeader(AsyncNotifyService.NOTIFY_HEADER_LAST_MODIFIED);
        long lastModifiedTs = StringUtils.isEmpty(lastModified) ? -1 : Long.parseLong(lastModified);
        // 配置发生变动的机器ip地址
        String handleIp = request.getHeader(AsyncNotifyService.NOTIFY_HEADER_OP_HANDLE_IP);
        dumpService.dump(dataId, group, tenant, tag, lastModifiedTs, handleIp);
        return true;
    }
}
